/* INDEX OF COMPETITION, RUN-OFF elections */

/* NOTATION: id district, m district magnitude, v_i party i's vote share, s_i party i's no of seats */

use dta/SMD_Candidate_all_2, clear


foreach year in 1909 1912 1915 1918 {
preserve
keep if year==`year'

keep if round==1  /* ONLY INCLUDE FIRST ROUND */
drop if party=="spr"
egen totalvotes_wo_spr=sum(votes), by(valgkrets)
replace votesh=votes/totalvotes_wo_spr

** "The minimum value should obtain if one candidate/party receives all the votes."
** "For two-candidolte pluraliry elections. the measure should reduce to a simple function of the difference in vote share between the winner olnd the loser."

rename valgkrets id
gen m=1
rename winner s_i   /* this is the first-round front-runner which is dubbed "winner", i.e. we assume that first-round is FPTP */
rename votesh v_i

*reshape long s_i v_i, i(id) 
*replace s_i=. if v_i==0
*replace v_i=. if v_i==0

/* Maximum vote share required for party i to gain an additional seat */

gen T_E = 1/(m+1)    /* T_E Threshold of exclusion */

gen x_G =(s_i+1)/(m+1)-v_i
replace x_G =. if s_i==m|x_G>T_E


/* Identify runner up j's vote share v_j and number of seats s_j */

gen s=0    /* counts seats allocated */
gen ss=0    /* counts sum of seats allocated */
gen pv=v_i    /* electoral quotient */
gen v_j=.
gen s_j=.
bys id year: egen nop=count(pv)    /*nop number of parties */
set more off
forval i=1/35 {        /* maximum number of rounds to allocate all the seats is 35 (=m) */
bys id year: egen r=rank(pv), u    /* this ranks the electoral quotients */
replace s=s+1 if r==nop&ss<m
gsort id year -r
replace v_j=v_i[_n+1] if r==nop&s==s_i&s_i>0
replace s_j=s_i[_n+1] if r==nop&s==s_i&s_i>0
replace pv=v_i/(s+1) if r==nop&ss<m
replace ss=ss+1 if ss<m
drop r
}

drop s-pv


/* Minimum vote share that could cost party i a seat */

gen x_L = (-s_i*v_j+s_j*v_i+v_i)/(s_i+s_j+1)


/* Indices of competition (C1, C2) */

gen c1_i = max(T_E-x_G, T_E-x_L) / T_E
sum c1_i

gen c2_i = 1-2*min(x_G, x_L)
sum c2_i


****************************************************

gen C1=c1_i*v_i
gen C2=c2_i*v_i

gen CandidateRunning=v_i>0
collapse (mean) margin (sum) C1 (sum) C2 (sum) CandidateRunning, by(id)

****************************************************
*scatter C1 margin
*scatter C1 margin if Candidate==2 /** "For two-candidolte pluraliry elections. the measure should reduce to a simple function of the difference in vote share between the winner olnd the loser." */

gen year=`year'
gen SMD_district=id
sort year SMD_district
save dta\GS`year'.dta, replace 
restore
}

